package com.pzh.assignment.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pzh.assignment.common.bean.Result;
import com.pzh.assignment.common.bean.vo.PlanVO;
import com.pzh.assignment.common.shiro.ShiroUtils;
import com.pzh.assignment.entity.Groups;
import com.pzh.assignment.entity.Major;
import com.pzh.assignment.service.IGroupsService;
import com.pzh.assignment.service.IMajorService;
import com.pzh.assignment.service.IPlanService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author pengzhihao
 * @since 2022-04-16
 */
@RestController
@RequestMapping("/plan")
public class PlanController {

    @Autowired
    IPlanService planService;
    @Autowired
    IMajorService majorService;
    @Autowired
    IGroupsService groupsService;

    @RequiresRoles(value = {"sys_admin", "admin"}, logical = Logical.OR)
    @GetMapping
    public Result listPlanByPage(@RequestParam(defaultValue = "1") Integer currentPage,
                                    @RequestParam(defaultValue = "5") Integer size) {
        Page<PlanVO> page = new Page<>(currentPage, size);
        IPage<PlanVO> pageData = planService.findPlanVOByPage(page);

        //去除不属于当前用户所属学院的专业的教学计划记录
        Integer groupId = ShiroUtils.getProfile().getGroupId();
        Groups group = groupsService.getById(groupId);
        List<Major> majorList = majorService.list(new QueryWrapper<Major>().eq("college_id", group.getCollegeId()));
        List<Integer> majorIds = majorList.stream().map(major -> major.getId()).collect(Collectors.toList());
        List<PlanVO> planVOList = pageData.getRecords();
        Iterator<PlanVO> iterator = planVOList.iterator();
        while (iterator.hasNext()){
            PlanVO vo = iterator.next();
            if (! majorIds.contains(vo.getProgram().getMajorId())){
                iterator.remove();
            }
        }
        //todo 通过内存中筛选数据的方式会导致分页不准确，待解决
//        int total = planVOList.size();
//        int pages = total % size == 0 ? total / size : total / size + 1;
//        pageData.setTotal(total);
//        pageData.setPages(pages);
        pageData.setRecords(planVOList);
        return Result.success(pageData);
    }

}
